package ctbu.edu.cn.thydemo.service;

import ctbu.edu.cn.thydemo.domain.Student;
import ctbu.edu.cn.thydemo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;


    public Page<Student> getUserList(int pageNum, int pageSize) {
        Sort.Order order=new Sort.Order(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(order));
        Page<Student> users = studentRepository.findAll(pageable);
        return users;
    }



    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    /**
     * 按id进行查询
     * @param id 主键，整数
     * @return
     */
    public Student findById(Integer id){

        Student student =studentRepository.findById(id).orElse(null);
        return student;
    }


    /**
     * 按名字进行查询
     * @param name
     * @return
     */
    public List<Student> findBySname(String name){
        return studentRepository.findBySnameLike(name);
    }


    /**
     * 按名字和学号进行查询
     * @param name
     * @param sno
     * @return
     */
    public List<Student> findBySnameAndSno(String name,String sno){

        return studentRepository.findBySnameAndSno(name,sno);
    }

    public Student insert(Student student){
        studentRepository.save(student);
        return student;
    }

    public Student update(Student student){

        return studentRepository.save(student);
    }

//    public void delete(Integer id){
//        studentRepository.deleteById(id);
//    }
//    public void delete(Student student){
//        studentRepository.delete(student);
//    }

    public void delete(Integer id){
        Student student = new Student();
        student.setId(id);
        studentRepository.delete(student);
    }
}
